package org.example;

import org.example.entity.Order;
import org.example.entity.Product;
import org.example.service.ItemService;
import org.example.service.OrderService;
import org.example.service.ProductService;
import org.example.service.UserService;
import org.example.service.impl.ItemServiceImpl;
import org.example.service.impl.OrderServiceImpl;
import org.example.service.impl.ProductServiceImpl;
import org.example.service.impl.UserServiceImpl;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class EcommerceSystem extends JFrame {
    private UserService userService = new UserServiceImpl();
    private ProductService productService = new ProductServiceImpl();
    private OrderService orderService = new OrderServiceImpl();
    private ItemService itemService = new ItemServiceImpl();

    private JTabbedPane tabbedPane;
    private JTextArea outputArea;
    private boolean currentUser;
    private CardLayout cardLayout;
    private JPanel contentPanel;
    private JTextArea infoTextArea;
    private Image backgroundImage;

    private static final Font MAIN_FONT = new Font("仿宋", Font.PLAIN, 20);
    private static final Color PRIMARY_COLOR = new Color(50, 125, 185);
    private static final Color BACKGROUND_COLOR = new Color(255, 255, 255);

    public EcommerceSystem() {
        setTitle("商品订单查询系统");
        setSize(700, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        getContentPane().setBackground(BACKGROUND_COLOR);

        // 加载主界面背景图 back2.jpg
        ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("back2.jpg"));
        if (icon != null) {
            backgroundImage = icon.getImage();
        } else {
            System.err.println("背景图片加载失败：back2.jpg 未找到");
        }

        JPanel loginPanel = createLoginPanel();
        add(loginPanel);

        setVisible(true);
    }

    private JPanel createLoginPanel() {
        JPanel panel = new JPanel(new GridBagLayout()) {
            private Image backgroundImage;

            {
                ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("background.jpg"));
                if (icon != null) {
                    backgroundImage = icon.getImage();
                } else {
                    System.err.println("登录背景图片加载失败：background.jpg 未找到");
                }
            }

            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (backgroundImage != null) {
                    g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
                }
            }
        };
        panel.setBackground(BACKGROUND_COLOR);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);

        JLabel titleLabel = new JLabel("登录界面");
        titleLabel.setFont(new Font("隶书", Font.BOLD, 30));
        titleLabel.setForeground(Color.WHITE);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(titleLabel, gbc);
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.WEST;

        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(MAIN_FONT);
        usernameLabel.setForeground(Color.WHITE);
        JTextField usernameField = new JTextField(20);
        usernameField.setFont(MAIN_FONT);
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(MAIN_FONT);
        passwordLabel.setForeground(Color.WHITE);
        JPasswordField passwordField = new JPasswordField(20);
        passwordField.setEchoChar('*');
        passwordField.setFont(MAIN_FONT);
        JButton loginButton = new JButton("登录 ");
        loginButton.setFont(MAIN_FONT);
        loginButton.setBackground(PRIMARY_COLOR);
        loginButton.setForeground(Color.WHITE);
        loginButton.setFocusPainted(false);

        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(usernameLabel, gbc);
        gbc.gridx = 1;
        panel.add(usernameField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(passwordLabel, gbc);
        gbc.gridx = 1;
        panel.add(passwordField, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.NONE;
        panel.add(loginButton, gbc);

        loginButton.addActionListener(e -> {
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword()).trim();

            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空！");
                return;
            }

            boolean user = userService.login(username, password);
            if (user) {
                currentUser = user;
                showMainUI();
            } else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误！");
            }
        });

        return panel;
    }

    private void showMainUI() {
        getContentPane().removeAll();
        setLayout(new BorderLayout());

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("菜单");

        DefaultMutableTreeNode queryProductPrice = new DefaultMutableTreeNode("查询商品价格");
        root.add(queryProductPrice);

        DefaultMutableTreeNode viewOrder = new DefaultMutableTreeNode("查看订单");
        viewOrder.add(new DefaultMutableTreeNode("按 ID 查询"));
        viewOrder.add(new DefaultMutableTreeNode("查看所有订单"));
        root.add(viewOrder);

        DefaultMutableTreeNode addProduct = new DefaultMutableTreeNode("添加商品");
        root.add(addProduct);

        DefaultMutableTreeNode queryOrderItems = new DefaultMutableTreeNode("查询订单商品");
        root.add(queryOrderItems);

        root.add(new DefaultMutableTreeNode("退出"));

        JTree tree = new JTree(root);
        tree.setCellRenderer(new CustomTreeCellRenderer());
        tree.setRowHeight(30);

        tree.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                TreePath path = tree.getPathForLocation(e.getX(), e.getY());
                if (path != null) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                    String selectedMenu = node.getUserObject().toString();
                    switch (selectedMenu) {
                        case "退出":
                            int result = JOptionPane.showConfirmDialog(EcommerceSystem.this, "确认退出吗？");
                            if (result == JOptionPane.OK_OPTION) {
                                System.exit(0);
                            }
                            break;
                        case "查询商品价格":
                            cardLayout.show(contentPanel, "ProductPricePanel");
                            break;
                        case "按 ID 查询":
                            cardLayout.show(contentPanel, "OrderByIdPanel");
                            break;
                        case "查看所有订单":
                            cardLayout.show(contentPanel, "AllOrdersPanel");
                            break;
                        case "添加商品":
                            cardLayout.show(contentPanel, "AddProductPanel");
                            break;
                        case "查询订单商品":
                            cardLayout.show(contentPanel, "OrderItemsPanel");
                            break;
                    }
                }
            }
        });

        JScrollPane menuScrollPanel = new JScrollPane(tree);
        menuScrollPanel.setBorder(BorderFactory.createEmptyBorder());
        menuScrollPanel.getViewport().setBackground(new Color(50, 50, 50));

        cardLayout = new CardLayout();
        // 让内容面板支持背景绘制且子组件透明
        contentPanel = new JPanel(cardLayout) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (backgroundImage != null) {
                    g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
                }
            }

            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        contentPanel.add(createProductPricePanel(), "ProductPricePanel");
        contentPanel.add(createOrderByIdPanel(), "OrderByIdPanel");
        contentPanel.add(createAllOrdersPanel(), "AllOrdersPanel");
        contentPanel.add(createAddProductPanel(), "AddProductPanel");
        contentPanel.add(createOrderItemsPanel(), "OrderItemsPanel");

        infoTextArea = new JTextArea() {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        infoTextArea.setEditable(false);
        JScrollPane infoScrollPane = new JScrollPane(infoTextArea) {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        infoScrollPane.getViewport().setOpaque(false);

        JSplitPane contentInfoSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, contentPanel, infoScrollPane);
        contentInfoSplitPane.setDividerLocation(300);
        contentInfoSplitPane.setOneTouchExpandable(true);
        contentInfoSplitPane.setOpaque(false);

        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, menuScrollPanel, contentInfoSplitPane);
        mainSplitPane.setDividerLocation(150);
        mainSplitPane.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, new Color(60, 60, 60)));

        add(mainSplitPane, BorderLayout.CENTER);

        repaint();
        revalidate();
    }

    // 所有功能面板都要设置成透明，避免遮挡背景
    private JPanel createProductPricePanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10)) {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        panel.setBackground(BACKGROUND_COLOR);

        JLabel nameLabel = new JLabel("商品名称:");
        nameLabel.setFont(MAIN_FONT);
        JTextField nameField = new JTextField(20);
        nameField.setFont(MAIN_FONT);
        JButton queryButton = new JButton("查询价格");
        queryButton.setFont(MAIN_FONT);
        queryButton.setBackground(PRIMARY_COLOR);
        queryButton.setForeground(Color.WHITE);
        queryButton.setFocusPainted(false);

        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(queryButton);

        queryButton.addActionListener(e -> {
            String proName = nameField.getText().trim();
            if (proName.isEmpty()) {
                infoTextArea.setText("请输入商品名称！");
                return;
            }

            double price = productService.getPriceByProName(proName);
            if (price > 0) {
                infoTextArea.setText("商品【" + proName + "】的价格为：" + price + "元");
            } else {
                infoTextArea.setText("未找到商品【" + proName + "】的信息！");
            }
        });

        return panel;
    }

    private JPanel createOrderByIdPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10)) {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        panel.setBackground(BACKGROUND_COLOR);

        JLabel idLabel = new JLabel("订单 ID:");
        idLabel.setFont(MAIN_FONT);
        JTextField idField = new JTextField(10);
        idField.setFont(MAIN_FONT);
        JButton queryByIdButton = new JButton("按 ID 查询");
        queryByIdButton.setFont(MAIN_FONT);
        queryByIdButton.setBackground(PRIMARY_COLOR);
        queryByIdButton.setForeground(Color.WHITE);
        queryByIdButton.setFocusPainted(false);

        panel.add(idLabel);
        panel.add(idField);
        panel.add(queryByIdButton);

        queryByIdButton.addActionListener(e -> {
            String idText = idField.getText().trim();
            if (idText.isEmpty()) {
                infoTextArea.setText("请输入订单 ID！");
                return;
            }

            try {
                int ordId = Integer.parseInt(idText);
                Order order = orderService.getOrdById(ordId);
                if (order != null) {
                    infoTextArea.setText(formatOrderInfo(order));
                } else {
                    infoTextArea.setText("未找到订单 ID：" + ordId);
                }
            } catch (NumberFormatException ex) {
                infoTextArea.setText("请输入有效的订单 ID（数字）！");
            }
        });

        return panel;
    }

    private JPanel createAllOrdersPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10)) {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        panel.setBackground(BACKGROUND_COLOR);

        JButton queryAllButton = new JButton("查看所有订单");
        queryAllButton.setFont(MAIN_FONT);
        queryAllButton.setBackground(PRIMARY_COLOR);
        queryAllButton.setForeground(Color.WHITE);
        queryAllButton.setFocusPainted(false);

        panel.add(queryAllButton);

        queryAllButton.addActionListener(e -> {
            List<Order> orders = orderService.getAllOrd();
            if (orders.isEmpty()) {
                infoTextArea.setText("暂无订单数据！");
                return;
            }

            StringBuilder sb = new StringBuilder("所有订单信息：\n");
            for (Order order : orders) {
                sb.append(formatOrderInfo(order)).append("\n");
            }
            infoTextArea.setText(sb.toString());
        });

        return panel;
    }

    private String formatOrderInfo(Order order) {
        return "订单 ID：" + order.getOrderId() + "\n" +
                "用户 ID：" + order.getUserId() + "\n" +
                "订单金额：" + order.getTotalAmount() + "元\n" +
                "订单状态：" + order.getOrderStatus() + "\n" +
                "创建时间：" + order.getCreateTime() + "\n" +
                "支付时间：" + order.getPayTime();
    }

    private JPanel createAddProductPanel() {
        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10)) {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        panel.setBackground(BACKGROUND_COLOR);

        JLabel nameLabel = new JLabel("商品名称:");
        nameLabel.setFont(MAIN_FONT);
        JTextField nameField = new JTextField();
        nameField.setFont(MAIN_FONT);
        JLabel stockLabel = new JLabel("库存数量:");
        stockLabel.setFont(MAIN_FONT);
        JTextField stockField = new JTextField();
        stockField.setFont(MAIN_FONT);
        JLabel priceLabel = new JLabel("商品价格:");
        priceLabel.setFont(MAIN_FONT);
        JTextField priceField = new JTextField();
        priceField.setFont(MAIN_FONT);
        JButton addButton = new JButton("添加商品");
        addButton.setFont(MAIN_FONT);
        addButton.setBackground(PRIMARY_COLOR);
        addButton.setForeground(Color.WHITE);
        addButton.setFocusPainted(false);

        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(stockLabel);
        panel.add(stockField);
        panel.add(priceLabel);
        panel.add(priceField);
        panel.add(new JLabel());
        panel.add(addButton);

        addButton.addActionListener(e -> {
            String proName = nameField.getText().trim();
            String stockText = stockField.getText().trim();
            String priceText = priceField.getText().trim();

            if (proName.isEmpty() || stockText.isEmpty() || priceText.isEmpty()) {
                infoTextArea.setText("请填写完整商品信息！");
                return;
            }

            try {
                int stock = Integer.parseInt(stockText);
                double price = Double.parseDouble(priceText);

                Product product = new Product(0, proName, stock, price);
                productService.addPro(product);

                infoTextArea.setText("商品【" + proName + "】添加成功！");
                nameField.setText("");
                stockField.setText("");
                priceField.setText("");
            } catch (NumberFormatException ex) {
                infoTextArea.setText("库存（数字）或价格（数字）格式错误！");
            }
        });

        return panel;
    }

    //
    private JPanel createOrderItemsPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10)) {
            @Override
            public boolean isOpaque() {
                return false;
            }
        };
        panel.setBackground(BACKGROUND_COLOR);

        JLabel orderIdLabel = new JLabel("订单 ID:");
        orderIdLabel.setFont(MAIN_FONT);
        JTextField orderIdField = new JTextField(10);
        orderIdField.setFont(MAIN_FONT);
        JButton queryButton = new JButton("查询商品");
        queryButton.setFont(MAIN_FONT);
        queryButton.setBackground(PRIMARY_COLOR);
        queryButton.setForeground(Color.WHITE);
        queryButton.setFocusPainted(false);

        panel.add(orderIdLabel);
        panel.add(orderIdField);
        panel.add(queryButton);

        // 查询逻辑：调用 ItemService
        queryButton.addActionListener(e -> {
            String idText = orderIdField.getText().trim();
            if (idText.isEmpty()) {
                infoTextArea.setText("请输入订单 ID！");
                return;
            }

            try {
                int orderId = Integer.parseInt(idText);
                // 修正此处，确保返回的是商品名称列表
                List<String> productNames = itemService.getProductNamesByOrderId(orderId);

                if (productNames.isEmpty()) {
                    infoTextArea.setText("订单 ID【" + orderId + "】无商品或不存在！");
                } else {
                    StringBuilder sb = new StringBuilder("订单 ID【" + orderId + "】包含商品：\n");
                    for (String name : productNames) {
                        sb.append("- ").append(name).append("\n");
                    }
                    infoTextArea.setText(sb.toString());
                }
            } catch (NumberFormatException ex) {
                infoTextArea.setText("请输入有效的订单 ID（数字）！");
            }
        });

        return panel;
    }

    static class CustomTreeCellRenderer extends DefaultTreeCellRenderer {
        private final Icon folderIcon = UIManager.getIcon("FileView.directoryIcon");
        private final Icon fileIcon = UIManager.getIcon("FileView.fileIcon");

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                                                      boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            if (value instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                if (!node.isLeaf()) {
                    setIcon(folderIcon);
                } else {
                    setIcon(fileIcon);
                }
            }
            return this;
        }
    }

    // 程序入口：启动 Swing 界面
    public static void main(String[] args) {
        SwingUtilities.invokeLater(EcommerceSystem::new);
    }
}